package com.suitsoft.bdms.commos;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 定时同步 启动线程类
 *@author Suine
 */
public class SyncUserTimer {
	/** 日志输出对象 */
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	/**数据库的配置  只对设置定时的系统*/
	private List<Map<String,Object>> dbTimer;
	/** 已实例化的Timer对象  用与销毁线程*/
	private List<Timer> timerList;
	/** 系统运行参数 */
	AppConfig config = AppConfig.getInstance();
	
	public SyncUserTimer(List<Map<String, Object>> dbTimer) {
		this.dbTimer = dbTimer;
		//初始化时 把原来所有定时执行全部取消.
		destroy();
	}

	public void init(){
		logger.info("准备定时线程");
		Timer timer = null;
		timerList = new ArrayList<Timer>();
		for(Map<String,Object> m : dbTimer){
			timer = new Timer();
			try {
				String viewName = m.get("VIEW_NAME") == null ? "" : m.get("VIEW_NAME").toString();
				Long time = m.get("TIMER_MINI") == null ? 0L : Long.valueOf(m.get("TIMER_MINI").toString());
				time = 1000 * 60 * time;
				//项目启动后一个小时，第一次同步
				timer.schedule(new SyncUserThread(viewName),1000 * 3600,time);
//				timer.schedule(new SyncUserThread(viewName),time,time);
				timerList.add(timer);
			} catch (Exception e) {
				timer.cancel();
				e.printStackTrace();
				logger.info("初始化定时同步账户线程 失败");
			}
		}
		config.setTimerList(timerList);
		if(timerList == null || timerList.isEmpty()){
			logger.info("没有定时时间，不启动线程");
		}else{
			logger.info("定时线程启动成功.");
		}
	}
	
	public void destroy(){
		timerList = config.getTimerList();
		if(timerList != null && !timerList.isEmpty()){
			logger.info("正在销毁定时线程..");
			for(Timer timer : timerList){
				timer.cancel();
			}
			logger.info("销毁定时线程 完成！");
		}
	}

}

